using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Net;
using IGGCore;
using System.Resources;

namespace IGGWindowApp
{
    public class PlayerParser
    {
        /// <summary>
        /// Download a player picture from the cnssi website
        /// </summary>
        public static Image DownloadPlayerPicture(string id)
        {
            Image result = null;
            Stream stream = null;
            try
            {
                WebClient client = new WebClient();
                // 425883.jpg
                stream = client.OpenRead("http://mlb.mlb.com/images/players/mugshot/ph_" + id + WindowConstants.IMAGE_EXTENSION);
                result = new Bitmap(stream);
                stream.Flush();
                stream.Close();
            }
            catch { }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                string path = Application.StartupPath + WindowConstants.FOLDER_PATH_PLAYERS;
                if (result == null)
                {
                    result = Properties.Resources.unknown;
                }
            }
            return result;
        }

        /// <summary>
        /// Return the specified player picture
        /// </summary>
        public static Image GetPlayerImage(string firstName, string lastName, string team)
        {
            string path = Application.StartupPath + WindowConstants.FOLDER_PATH_PLAYERS;
            Image result = GetDownloadedPicture(firstName, lastName, team);

            StreamReader reader = null;
            string content = null;
            if (result == null)
            {
                result = new Bitmap(path + WindowConstants.FILE_UNKNOWN_PLAYER_PIC);
                TeamIdentification teamId = TeamIdentification.GetTeam(team);
                if (teamId != null)
                {
                    try
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(teamId.CNNSIPage);
                        reader = new StreamReader(request.GetResponse().GetResponseStream());
                        content = reader.ReadToEnd();
                    }
                    catch { }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    if (content != null)
                    {
                        string nameToFind = lastName + ", " + firstName;
                        int i = content.IndexOf(nameToFind);
                        if (i > -1)
                        {
                            int pos = i - 30;
                            int index = content.IndexOf("players", pos);
                            if (index > -1)
                            {
                                int indexEnd = content.IndexOf("/\"", index + 8);
                                string playerId = content.Substring(index + 8, indexEnd - (index + 8));
                                string playerURL = WindowConstants.URL_CNNSI_PLAYERS + playerId;
                                Image downloaded = DownloadPlayerPicture(team, firstName, lastName, playerId);
                                if (downloaded != null)
                                {
                                    result = downloaded;
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Download a player picture from the cnssi website
        /// </summary>
        private static Image DownloadPlayerPicture(string team, string firstName, string lastName, string id)
        {
            Image result = null;
            Stream stream = null;
            try
            {
                WebClient client = new WebClient();
                stream = client.OpenRead(WindowConstants.URL_CNNSI_PLAYER_PIC_FOLDER + id + WindowConstants.IMAGE_EXTENSION);
                result = new Bitmap(stream);
                stream.Flush();
                stream.Close();

                string path = Application.StartupPath + WindowConstants.FOLDER_PATH_PLAYERS + "//" + team;
                if (Directory.Exists(path) == false)
                {
                    Directory.CreateDirectory(path);
                }
                string filePath = path + "//" + firstName.ToLower() + "_" + lastName.ToLower() + WindowConstants.IMAGE_EXTENSION;
                result.Save(filePath);
            }
            catch { }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
            }
            return result;
        }

        /// <summary>
        /// Retrieve a downloaded player picture from the right team folder
        /// </summary>
        private static Image GetDownloadedPicture(string firstName, string lastName, string city)
        {
            Image result = null;
            string path = Application.StartupPath + WindowConstants.FOLDER_PATH_PLAYERS + "//" + city;
            if (Directory.Exists(path))
            {
                string playerFile = path + "//" + firstName.ToLower() + "_" + lastName.ToLower();
                if (File.Exists(playerFile + ".png"))
                {
                    result = new Bitmap(playerFile + ".png");
                }
                else if (File.Exists(playerFile + WindowConstants.IMAGE_EXTENSION))
                {
                    result = new Bitmap(playerFile + WindowConstants.IMAGE_EXTENSION);
                }
                else if (File.Exists(playerFile + ".gif"))
                {
                    result = new Bitmap(playerFile + ".gif");
                }
            }
            return result;
        }

    }
}
